<?php
// +----------------------------------------------------------------------
// | 有理想的地方，地狱都是天堂。
// +----------------------------------------------------------------------
// | Copyright @ df81.com 版权所有
// +----------------------------------------------------------------------
// | 作者: 南国老符 邮箱：1062129401@qq.com
// +----------------------------------------------------------------------

namespace app\admin\model;
use think\Model;
use think\facade\Db;

class Language extends Model{
	//目录
    protected function setMuluAttr(){
        // 转为小写字母
        $general = new \common\General();
        $mulu = $general->capital_to_underline(input('mulu'));
        
		return $mulu;
    }
	
    //新增编辑
	static function edit($id){
        $id = input('id'); $mulu = input('mulu'); $settheme = input('settheme'); $oldModule = config('app.default_app');
        $rootPath = app()->getRootPath(); $appPath = app()->getBasePath();
        $rs = Language::find($id);
        
        // 加载前端配置文件
        $separator = DIRECTORY_SEPARATOR;
        $langConfig = app()->getBasePath().$mulu.$separator.'config'.$separator.'template.php';
        $configArray = include($langConfig);
        $oldSetTheme = $rs['settheme']; $oldTemplate = $configArray['theme']; $oldMulu = $rs['mulu'];
        $dofile = new \common\Dofile();
        $auth = new \common\Auth(); $auth->check('','');
            
	    if($id>0){//编辑
			$result = $rs->save(input('post.'));
		}else{//新增
			$rs = new Language;
			$result = $rs->save(input('post.'));
            
			/*创建新语言模块 开始*/
			$oldLangRs = Db::name('language')->where('isdefault',1)->find();
    	    $oldDefaultMulu = $oldLangRs['mulu'];
    	    //创建模块目录及文件
    	    $fromModule = $appPath.$oldDefaultMulu;
    	    $toModule = $appPath.$mulu;
    	    $dofile->copyFile($fromModule,$toModule);
            // 重命名路由文件
            // rename($appPath.$mulu.$separator.'route'.$separator.$oldDefaultMulu.'.php',$appPath.$mulu.$separator.'route'.$separator.$mulu.'.php');
    	    
            //创建语言模板
    	    // $fromTemplate = $rootPath.'template'.$separator.$configArray['theme'].$separator.$oldDefaultMulu;
    	    // $toTemplate = $rootPath.'template'.$separator.$configArray['theme'].$separator.$mulu;
    	    // $dofile->copyFile($fromTemplate,$toTemplate);
    	    //创建后台语言包文件
    	    $fromAdminLang = $appPath.'admin'.$separator.'lang'.$separator.$oldDefaultMulu.'.php';
    	    $toAdminLang = $appPath.'admin'.$separator.'lang'.$separator.$mulu.'.php';
    	    copy($fromAdminLang,$toAdminLang);

    	    //往数据表site里添加模块数据
    	    $siteRs = Db::name('site')->where('lang',$oldDefaultMulu)->find();
    	    $tableName = config('database.connections.mysql.prefix').'site';
    	    $tableSQL = Db::query("desc $tableName");
    	    $tableFieldList = array();
    	    //读取表site里的字段
    	    foreach ($tableSQL as $sqlRs){
    	        if($sqlRs['Field'] != 'id'){
    	            if($sqlRs['Field'] != 'lang'){
    	                $tableFieldList[$sqlRs['Field']] = $siteRs[$sqlRs['Field']];
    	            }else{
    	                $tableFieldList[$sqlRs['Field']] = $mulu;
    	            }
    	        }
    	    }
    	    Db::name('site')->insert($tableFieldList);
    	    //往数据表module里添加模块数据
    	    $moduleRs = Db::name('module')->where('lang',$oldDefaultMulu)->select();
    	    $tableName = config('database.connections.mysql.prefix').'module';
    	    $tableSQL = Db::query("desc $tableName");
    	    $tableFieldList = array();
    	    foreach($moduleRs as $k=>$v){
    	        //读取表module里的字段
    	        foreach ($tableSQL as $sqlRs){
    	            if($sqlRs['Field'] != 'id'){
    	                if($sqlRs['Field'] != 'lang'){
    	        	        $tableFieldList[$k][$sqlRs['Field']] = $v[$sqlRs['Field']];
    	                }else{
    	        	        $tableFieldList[$k][$sqlRs['Field']] = $mulu;
    	                }
    	            }
    	        }
    	    }
    	    Db::name('module')->insertAll($tableFieldList);
    	    //往数据表area里添加模块数据
    	    $areaRs = Db::name('area')->where('lang',$oldDefaultMulu)->find();
    	    $tableName = config('database.connections.mysql.prefix').'area';
    	    $tableSQL = Db::query("desc $tableName");
    	    $tableFieldList = array();
    	    //读取表area里的字段
    	    foreach ($tableSQL as $sqlRs){
    	        if($sqlRs['Field'] != 'id'){
    	            if($sqlRs['Field'] != 'lang'){
    	                $tableFieldList[$sqlRs['Field']] = $areaRs[$sqlRs['Field']];
    	            }else{
    	                $tableFieldList[$sqlRs['Field']] = $mulu;
    	            }
    	        }
    	    }
    	    Db::name('area')->insert($tableFieldList);
    	    //往数据表field里添加模块数据
    	    $fieldRs = Db::name('field')->where('lang',$oldDefaultMulu)->select();
    	    $tableName = config('database.connections.mysql.prefix').'field';
    	    $tableSQL = Db::query("desc $tableName");
    	    $tableFieldList = array();
    	    foreach($fieldRs as $k=>$v){
    	        //读取表field里的字段
    	        foreach ($tableSQL as $sqlRs){
    	            if($sqlRs['Field'] != 'id'){
    	                if($sqlRs['Field'] != 'lang'){
    	        	        $tableFieldList[$k][$sqlRs['Field']] = $v[$sqlRs['Field']];
    	                }else{
    	        	        $tableFieldList[$k][$sqlRs['Field']] = $mulu;
    	                }
    	            }
    	        }
    	    }
    	    Db::name('field')->insertAll($tableFieldList);
    	    //往数据表navigation里添加模块数据
    	    $navWhere[] = ['lang','=',$oldDefaultMulu]; $navWhere[] = ['parentid','=',0];
    	    $navigationRs = Db::name('navigation')->where($navWhere)->select();
    	    $tableName = config('database.connections.mysql.prefix').'navigation';
    	    $tableSQL = Db::query("desc $tableName");
    	    $tableFieldList = array();
    	    foreach($navigationRs as $k=>$v){
    	        //读取表navigation里的字段
    	        foreach ($tableSQL as $sqlRs){
    	            if($sqlRs['Field'] != 'id'){
    	                if($sqlRs['Field'] != 'lang'){
    	        	        if($sqlRs['Field'] != 'linkurl'){
    	        	            $tableFieldList[$k][$sqlRs['Field']] = $v[$sqlRs['Field']];
    	        	        }else{
    	        	            $navLinkurl = str_replace('/'.$oldDefaultMulu.'/','/'.$mulu.'/',$v['linkurl']);
    	        	            $tableFieldList[$k][$sqlRs['Field']] = $navLinkurl;
    	        	        }
    	                }else{
    	        	        $tableFieldList[$k][$sqlRs['Field']] = $mulu;
    	                }
    	            }
    	        }
    	    }
    	    Db::name('navigation')->insertAll($tableFieldList);
    	    //往数据表ad里添加模块数据
    	    $adRs = Db::name('ad')->where('lang',$oldDefaultMulu)->select();
    	    $tableName = config('database.connections.mysql.prefix').'ad';
    	    $tableSQL = Db::query("desc $tableName");
    	    $tableFieldList = array();
    	    foreach($adRs as $k=>$v){
    	        //读取表ad里的字段
    	        foreach ($tableSQL as $sqlRs){
    	            if($sqlRs['Field'] != 'id'){
    	                if($sqlRs['Field'] != 'lang'){
    	        	        if($sqlRs['Field'] != 'linkurl'){
    	        	            $tableFieldList[$k][$sqlRs['Field']] = $v[$sqlRs['Field']];
    	        	        }else{
    	        	            $adLinkurl = str_replace('/'.$oldDefaultMulu.'/','/'.$mulu.'/',$v['linkurl']);
    	        	            $tableFieldList[$k][$sqlRs['Field']] = $adLinkurl;
    	        	        }
    	                }else{
    	        	        $tableFieldList[$k][$sqlRs['Field']] = $mulu;
    	                }
    	            }
    	        }
    	    }
    	    Db::name('ad')->insertAll($tableFieldList);
            /*创建新语言模块 结束*/
		}

        /*修改配置文件的默认模块 开始*/
        $newLangRs = Db::name('language')->where('isdefault',1)->find();
        $newModule = $newLangRs['mulu'];
        if($newModule != $oldModule){
            $appFile = app()->getConfigPath().'app.php';
            $old = '\'default_app\'      => \''.$oldModule.'\',';
            $new = '\'default_app\'      => \''.$newModule.'\',';
            $dofile->editFile($appFile,$old,$new);
        }
        /*修改配置文件的默认模块 结束*/

        // 编辑状态下，如果改变了语言目录，则重命名语言目录名称等
        if(!empty($id) and $oldMulu != $mulu){
            // 重命名模块目录
            rename($appPath.$oldMulu,$appPath.$mulu);
            // 重命名模板目录
            rename($rootPath.'template'.$separator.$configArray['theme'].$separator.$oldMulu,$rootPath.'template'.$separator.$configArray['theme'].$separator.$mulu);
            // 重命名路由文件
            // rename($appPath.$mulu.$separator.'route'.$separator.$oldMulu.'.php',$appPath.$mulu.$separator.'route'.$separator.$mulu.'.php');
            // 重命名后台语言包
            rename($appPath.'admin'.$separator.'lang'.$separator.$oldMulu.'.php',$appPath.'admin'.$separator.'lang'.$separator.$mulu.'.php');
            // 更新site表里的lang字段
            Db::name('site')->where('lang',$oldMulu)->update(['lang'=>$mulu]);
            // 批量更新module表里的lang字段
            Db::name('module')->where('lang',$oldMulu)->update(['lang'=>$mulu]);
            // 更新area表里的lang字段
            Db::name('area')->where('lang',$oldMulu)->update(['lang'=>$mulu]);
            // 更新field表里的lang字段
            Db::name('field')->where('lang',$oldMulu)->update(['lang'=>$mulu]);
            // 更新navigation表里的lang字段
            Db::name('navigation')->where('lang',$oldMulu)->update(['lang'=>$mulu]);
            // 更新navigation表里的linkurl字段
            $navigationArr = Db::name('navigation')->where('lang',$oldMulu)->select();
            foreach ($navigationArr as $navRs) {
                if(strpos($navRs['linkurl'],"/$oldMulu/") !== false){
                    $linkurl = str_replace("/$oldMulu/","/$mulu/",$navRs['linkurl']);
                    Db::name('navigation')->where('linkurl',$navRs['linkurl'])->update(['linkurl'=>$linkurl]);
                }
            }
            // 更新ad表里的lang字段
            Db::name('ad')->where('lang',$oldMulu)->update(['lang'=>$mulu]);
        }

        /*如果修改了原模块目录或者是新增语言模块，则修改相关文件的语言标识，重命名语言文件 开始*/
        if(empty($id) or $oldMulu != $mulu){
            $editMulu = $appPath.$mulu.'/';
            $newFile = $dofile->getFiles($editMulu,true);//取得语言模块下的所有文件
            if(!empty($id)) $oldDefaultMulu = $oldMulu;
            foreach ($newFile as $catalog=>$fileValue){
                if(is_array($fileValue)){
                    foreach($fileValue as $subFileValue){
                        if(!is_array($subFileValue) and $catalog != 'lang'){
                            $dofile->editFile($editMulu.$catalog.'/'.$subFileValue,'\\'.$oldDefaultMulu.'\\','\\'.$mulu.'\\');
                        }else{//如果是语言包，则重命名
                            if(is_file($appPath.$mulu.'/lang/'.$oldDefaultMulu.'.php')){
                                rename($appPath.$mulu.'/lang/'.$oldDefaultMulu.'.php',$appPath.$mulu.'/lang/'.$mulu.'.php');
                            }
                        }
                    }
                }else{
                    $dofile->editFile($editMulu.$fileValue,'\\'.$oldDefaultMulu.'\\','\\'.$mulu.'\\');
                }
            }
            //修改路由文件
            // $dofile->editFile($appPath.$mulu.$separator.'route'.$separator.$mulu.'.php',$oldDefaultMulu.'/',$mulu.'/');
        }
        /*如果修改了原模块目录或者是新增语言模块，则修改相关文件的语言标识，重命名语言文件 结束*/
        
        /*修改前端配置文件：PC和移动端是否共用模板 开始*/
        $moduleAppFile = $appPath.$mulu.'/config/'.'template.php';
        if(file_exists($moduleAppFile)){
            $oldSetThemeStr = '\'theme\'=>\''.$oldTemplate.'\',\'settheme\'=>\''.$oldSetTheme.'\',\'skin\'=>\'/skin/index/'.$oldTemplate.'\'';
            $newSetThemeStr = '\'theme\'=>\''.input('template').'\',\'settheme\'=>\''.input('settheme').'\',\'skin\'=>\'/skin/index/'.input('template').'\'';
            $dofile->editFile($moduleAppFile,$oldSetThemeStr,$newSetThemeStr);
        }
        /*修改前端配置文件：PC和移动端是否共用模板 结束*/

		return $rs->id;
	}
	
	/**列表
    * signid 1启用，0不启用
    * keyword 关键词
    * order 排序
    */
	static function index($signid = 1, $keyword = '', $order = 'sequence desc'){
		$keyword = trim($keyword); $pageParam = array('lang'=>$lang);
        // 是否启用
		if(in_array($signid,array('0','1'))){
		    $where[] = ['signid','=',$signid];
		    $pageParam += array('lang'=>$lang);
		}
		// 关键词查找
		if(!empty($keyword)){
		    $where[] = ['admintitle|viewtitle','like',$keyword];
		    $pageParam += array('keyword'=>$keyword);
		}

		$rs = Db::name('language')->where($where)->order($order)
            ->paginate([
                'list_rows'=> 20,
                'query'=> $pageParam,
            ]);
        $rs = $rs->each(function($item, $key){
            if(config('global.url.bind_lang') == 1){
                $domainArray = config('app.domain_bind'); $default_lang = config('lang.default_lang');
                foreach ($domainArray as $domainKey => $domain){
                    if($domain == $item['mulu']){
                        if($item['mulu'] == $default_lang){
                            if(substr_count($domainKey,'.') == 1) $url = request()->scheme().'://'.$domainKey.'/';
                            if(strpos($domainKey,'www.') !== false) $url = request()->scheme().'://'.$domainKey.'/';
                        }else{
                            $url = request()->scheme().'://'.$domainKey.'/';
                        }
                    }
                }
            }else{
                $url = '/'.$item['mulu'].'/';
            }
            $item['url'] = $url;
            return $item;
        });
		return $rs;
	}
}